package org.jf.tool.fx.jftoolfx.encrypt.controller;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import org.jf.tool.fx.jftoolfx.common.BaseController;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
import java.util.ResourceBundle;

/**
 * @author jifeng_zhang
 * @date 2025/8/15 下午3:43
 */
public class HashController extends BaseController {

    @FXML
    public VBox main;
    @FXML
    public HBox fileBox;
    @FXML
    public TextField filePathField;
    @FXML
    private TextArea plainText;
    @FXML
    private TextArea result;
    @FXML
    public CheckBox upperCase;
    @FXML
    private ToggleGroup hashTypeGroup;
    @FXML
    private ToggleGroup myToggleGroup;

    @Override
    protected void init(URL url, ResourceBundle resourceBundle) {
    }

    @FXML
    private void changeType() {
        String type = myToggleGroup.getSelectedToggle().getUserData().toString();
        if ("1".equals(type)) {
            fileBox.setVisible(false);
            fileBox.setManaged(false);
            plainText.setVisible(true);
            plainText.setManaged(true);
        } else if ("2".equals(type)) {
            plainText.setVisible(false);
            plainText.setManaged(false);
            fileBox.setVisible(true);
            fileBox.setManaged(true);
        }
    }

    @FXML
    private void upload() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择要上传的文件");

        // 设置文件过滤器（可选）
        FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("所有文件 (*.*)", "*.*");
        fileChooser.getExtensionFilters().add(filter);
        // 设置初始目录为上次使用的目录
        if (LAST_DIRECTORY != null) {
            fileChooser.setInitialDirectory(LAST_DIRECTORY);
        } else {
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home")));
        }

        // 获取当前窗口
        File file = fileChooser.showOpenDialog(TOP_STAGE);
        if (file != null) {
            LAST_DIRECTORY = file.getParentFile();
            filePathField.setText(file.getAbsolutePath());
        } else {
            filePathField.setText("");
        }
    }

    @FXML
    private void encrypt() {
        String hash = hashTypeGroup.getSelectedToggle().getUserData().toString();
        String type = myToggleGroup.getSelectedToggle().getUserData().toString();
        String resultStr = "";
        if ("1".equals(type)) {
            String plain = plainText.getText();
            resultStr = hashByPlain(hash, plain);
        } else {
            File file = new File(filePathField.getText());
            if (file.exists()) {
                resultStr = md5ByFile(hash, file);
            } else {
                resultStr = "请先上传文件！";
            }
        }
        if (upperCase.isSelected()) {
            resultStr = resultStr.toUpperCase();
        }
        result.setText(resultStr);
    }

    @FXML
    private void clear() {
        plainText.setText("");
        result.setText("");
        filePathField.setText("");
    }

    private String hashByPlain(String hash, String plain) {
        try {
            MessageDigest md = MessageDigest.getInstance(hash);
            byte[] digest = md.digest(plain.getBytes(StandardCharsets.UTF_8));
            return HexFormat.of().formatHex(digest);
        } catch (NoSuchAlgorithmException e) {
            return "Error：" + e.getMessage();
        }
    }

    private String md5ByFile(String hash, File file) {
        try (InputStream is = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(is)) {
            MessageDigest md = MessageDigest.getInstance(hash);
            byte[] buffer = new byte[8192];
            int bytesRead;

            while ((bytesRead = bis.read(buffer)) != -1) {
                md.update(buffer, 0, bytesRead);
            }
            byte[] digest = md.digest();
            return HexFormat.of().formatHex(digest);
        } catch (Exception e) {
            return "Error：" + e.getMessage();
        }
    }

    @FXML
    private void copy(ActionEvent event) {
        copy(result.getText());
    }

}
